/**
 * 
 */
package com.xuyue.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author tony
 *
 */
public class HttpUtil {
	
	/**
	 * 
	 * @param method-POST , GET
	 * @param strURL
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String send(String method,String strURL, String params) throws Exception {
		String result = null;

		URL url = new URL(strURL);// 创建连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestMethod(method); // 设置请求方式
		connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
		connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
		connection.setRequestProperty("Accept-Encoding", "identity"); 
		connection.connect();
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
		out.append(params);
		out.flush();
		out.close();
		// 读取响应
		InputStream is = connection.getInputStream();
		 ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte[] buf = new byte[256];
         int length = -1;
         while((length = is.read(buf)) != -1){
             baos.write(buf,0,length);
         }
         is.close();
         result= new String(baos.toByteArray(),"UTF-8");// utf-8编码

		return result; // 自定义错误信息
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
